package com.azt.data.utils;

import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * HttpServletRequest帮助类
 * 
 * @author BaseLine
 * 
 */
public class RequestUtils {
	private static final Logger log = LoggerFactory.getLogger(RequestUtils.class);

	public static void MapToModelMap(Map<String, String> map, HttpServletRequest request) {
		for (Map.Entry<String, String> entry : map.entrySet()) {
			request.setAttribute(entry.getKey(), entry.getValue());
		}
	}

	/**
	 * 获取以so_开始的查询用的字段值
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, String> getSearchMap(HttpServletRequest request) {
		return getRequestMapWithPrefix(request, "so_");
	}

	public static Map<String, String> getRequestMapWithPrefix(HttpServletRequest request, String prefix) {
		return getRequestMap(request, prefix, true);
	}

	@SuppressWarnings("unchecked")
	private static Map<String, String> getRequestMap(HttpServletRequest request, String prefix, boolean nameWithPrefix) {

		boolean ispost = request.getMethod().equalsIgnoreCase("post");
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<String> names = request.getParameterNames();
		String name, key, value;
		while (names.hasMoreElements()) {
			name = names.nextElement();
			if (name.startsWith(prefix)) {
				key = nameWithPrefix ? name : name.substring(prefix.length());
				value = StringUtils.join(request.getParameterValues(name), ',');
				if (!ispost) {
					try {
						value = URLDecoder.decode(value, "UTF-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
				map.put(key, StrUtil.trim(value));
			}
		}
		return map;
	}

	/**
	 * 获取查询参数
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	public static String getQueryParam(HttpServletRequest request, String name) {
		if (StringUtils.isBlank(name)) {
			return null;
		}
		if (request.getMethod().equalsIgnoreCase("post")) {
			return request.getParameter(name);
		}
		String s = request.getQueryString();
		if (StringUtils.isBlank(s)) {
			return null;
		}
		try {
			s = URLDecoder.decode(s, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.error("encoding  utf-8 not support?", e);
		}
		String[] values = parseQueryString(s).get(name);
		if (values != null && values.length > 0) {
			return values[values.length - 1];
		} else {
			return null;
		}
	}

	public static Map<String, String[]> parseQueryString(String s) {
		String valArray[] = null;
		if (s == null) {
			throw new IllegalArgumentException();
		}
		Map<String, String[]> ht = new HashMap<String, String[]>();
		StringTokenizer st = new StringTokenizer(s, "&");
		while (st.hasMoreTokens()) {
			String pair = (String) st.nextToken();
			int pos = pair.indexOf('=');
			if (pos == -1) {
				continue;
			}
			String key = pair.substring(0, pos);
			String val = pair.substring(pos + 1, pair.length());
			if (ht.containsKey(key)) {
				String oldVals[] = (String[]) ht.get(key);
				valArray = new String[oldVals.length + 1];
				for (int i = 0; i < oldVals.length; i++) {
					valArray[i] = oldVals[i];
				}
				valArray[oldVals.length] = val;
			} else {
				valArray = new String[1];
				valArray[0] = val;
			}
			ht.put(key, valArray);
		}
		return ht;
	}

	/**
	 * 获取 整数参数
	 * @param request
	 * @param name
	 * @return
	 */
	public static Integer getInteger(HttpServletRequest request, String name) {
		return getInteger(request,name,null);
	}
	public static Integer getInteger(String name) {
		HttpServletRequest request = getRequest();
		return getInteger(request,name,null);
	}

	
	public static Integer getInteger(HttpServletRequest request, String name,Integer defaultval) {
		String value = request.getParameter(name);
		if(StringUtils.isBlank(value)){
			return defaultval;
		}
		if(StringUtils.isNumeric(value)){
			return Integer.parseInt(value);
		}
		return defaultval;
	}

	public static HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;

	}

	public static String getString(String name){
		return getString(getRequest(),name);
	}

	public static String getString(HttpServletRequest request, String name) {
		return getString(request,name,null);
	}

	public static String getString(HttpServletRequest request, String name,String defaultval) {
		String value = request.getParameter(name);
		if(StringUtils.isBlank(value)){
			return defaultval;
		}
		return value;
	}
	
	
	public static Boolean getBoolean(HttpServletRequest request, String name,Boolean defaultval){
		String value = request.getParameter(name);
		if(StringUtils.isBlank(value)){
			return defaultval;
		}
		return Boolean.valueOf(value);
	}
	public static Boolean getBoolean(String name,Boolean defaultval){
		String value = getRequest().getParameter(name);
		if(StringUtils.isBlank(value)){
			return defaultval;
		}
		return Boolean.valueOf(value);
	}

}
